package com.qianbei.user;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.common.utilis.IDCard;
import com.qianbei.user.login.CountryCodeActivity;
import com.qianbei.user.login.Login_regist_activity;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 绑定手机号码
 *
 * @author jiaowenzheng
 *
 * Created by user on 16/5/31.
 */
public class BindPhoneActivity extends BaseActivity{

    @Bind(R.id.et_mobile)
    EditText mPhoneEdit;
    @Bind(R.id.et_identifyingCode)
    EditText mIdentifyingCodeEdit;
    @Bind(R.id.register_getcode)
    TextView mRegisterGetCode;
    @Bind(R.id.tv_show_phone)
    TextView mShowPhoneTv;
    @Bind(R.id.tv_country_number)
    TextView mCountryNumberTv;
    @Bind(R.id.btn_confirm)
    Button mConfirmBtn;

    private String mCountryCode="86";
    private String mCountryName="中国";

    private String mWeChatInfo;
    private int mFromTarget = 1; // 1 从微信登录 到绑定手机号码  2 从设置 到修改手机号码


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
        ButterKnife.bind(this);

        setTitle(R.string.bind_phone);

        mWeChatInfo = getIntent().getStringExtra(ConstantValue.WE_CHAT_INFO_KEY);

        if (getIntent().getBooleanExtra(ConstantValue.SHOW_PHONE_KEY,false)){
            mFromTarget = 2;
            setTitle(R.string.modify_phone);
            mPhoneEdit.setHint(R.string.input_new_phone);
            mShowPhoneTv.setText(getString(R.string.show_phone_format,
                    TextUtils.isEmpty(SetData.getUserPhone()) ? "" : SetData.getUserPhone()));
            mShowPhoneTv.setVisibility(View.VISIBLE);
        }else{
            mShowPhoneTv.setVisibility(View.GONE);
        }


        mRegisterGetCode.setOnClickListener(this);
        mConfirmBtn.setOnClickListener(this);
        mCountryNumberTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.register_getcode:
                // 获取注册验证码
                registerCheck("1");
                hideSoftInputFromWindow();
                break;
            case R.id.btn_confirm:
                bindPhoneRequest();
                break;
            case R.id.tv_country_number:
                startActivityForResult(new Intent(this, CountryCodeActivity.class),1);
                break;
        }
    }

    /**
     *
     * 倒计时类
     *
     */
    private CountDownTimer timer = new CountDownTimer(60000,1000){

        @Override
        public void onTick(long millisUntilFinished) {
            if (mRegisterGetCode != null){
                mRegisterGetCode.setText(getString(R.string.format_verification_code,millisUntilFinished / 1000));
            }

        }

        @Override
        public void onFinish() {
            if (mRegisterGetCode != null){
                mRegisterGetCode.setClickable(true);
                mRegisterGetCode.setText(R.string.menu_register_tv_identifyingCode);
            }

        }
    };


    /**
     * 获取手机注册码
     *
     * 1:注册、2:忘记密码、3:更换手机号
     */
    private void registerCheck(final String type) {
        final String phoneNumber = mPhoneEdit.getText().toString().trim();

        if (TextUtils.isEmpty(phoneNumber)) {
            new MsgAlert().show(R.string.menu_login_activity_check_mobile_null);
            return ;
        }

        ServerControl sc = new ServerControl(URL_USER + "get_sms_code",
                "country_code",mCountryCode,
                "phone_number", phoneNumber,
                "type", type);
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                String msg = sr.bodyData.optString("msg");
                boolean registered = sr.bodyData.optBoolean("registered_flag");

                if (sr.isContinue) {
                    if (registered && mFromTarget == 1){
                        showTipDialog(phoneNumber);
                    }else{
                        new MsgAlert().show(msg);
                        mRegisterGetCode.setClickable(false);
                        timer.start();
                    }
                }else{
                    if (registered && mFromTarget == 1){
                        showTipDialog(phoneNumber);
                    }
                }
            }
        };
        new ProgressDialog(mContext).startControl(sc, "获取验证码");
    }

    public void showTipDialog(String phoneNumber){

        final StringBuilder sb = new StringBuilder(mWeChatInfo);
        sb.append("/@:/").append(phoneNumber);

        AlertDialog.Builder builder = new AlertDialog.Builder(BindPhoneActivity.this);
        builder.setMessage(R.string.register_tip);
        builder.setTitle(R.string.tip_title);
        builder.setPositiveButton("q", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent =new Intent(BindPhoneActivity.this,Login_regist_activity.class);
                intent.putExtra(ConstantValue.SELECT_TAB_KEY,true);
                intent.putExtra(ConstantValue.WE_CHAT_INFO_KEY,sb.toString());
                startActivity(intent);
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.create().show();
    }


    /**
     *
     * 绑定手机号码
     *
     */
    public void bindPhoneRequest(){

        final String phone = mPhoneEdit.getText().toString().trim();
        String verificationCode = mIdentifyingCodeEdit.getText().toString().trim();

        if (TextUtils.isEmpty(phone)){
            new MsgAlert().show(R.string.menu_login_activity_check_mobile_null);
            return;
        }

        if ("86".equals(mCountryCode) && !IDCard.isMobileNO(phone)){
            new MsgAlert().show(R.string.menu_login_activity_check_mobile_format);
            return;
        }

        if (TextUtils.isEmpty(verificationCode)){
            new MsgAlert().show(R.string.empty_verification_code);
            return;
        }

        ServerControl sc = new ServerControl(BIND_PHONE_URL,
                "country_code",mCountryCode,
                "phone_number", phone,
                "captcha",verificationCode
        );

        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {

                    if (sr.bodyData != null){
                        new MsgAlert().show(sr.bodyData.optString("msg"));
                    }

                    timer.cancel();
                    SetData.setUserPhone(phone);

                    setResult(RESULT_OK);
                    finish();
                }
            }
        };
        new ProgressDialog(mContext).startControl(sc,getString(R.string.loading));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode && data != null){
            mCountryCode = data.getStringExtra(ConstantValue.COUNTRY_CODE_KEY);
            mCountryName = data.getStringExtra(ConstantValue.COUNTRY_NAME_KEY);
            mCountryNumberTv.setText(getString(R.string.country_code_format,mCountryName,mCountryCode));
        }
    }
}
